<template>
  <div class="bg-img pdf-list"></div>
</template>
<script>
import html2canvas from 'html2canvas'
import workerSrc from 'pdfjs-dist/legacy/build/pdf.worker.entry'
let PDFJS = require('pdfjs-dist/legacy/build/pdf.js')
PDFJS.GlobalWorkerOptions.workerSrc = workerSrc

export default {
  name: 'pdftoimage',
  data () {
    return {
      visible: false,
      open: false,
      canvasArr: [],
      loading: false,
      scale: 2,
      renderImgArr: [],
      ds: [],
      pdfText: 'pdf',
      allList: []
    }
  },
  methods: {
    /**
     * base64转为文件流
     * urlString: base64图片格式字符串
     * filename：文件名称
     */
    base64toFile (urlString, fileName) {
      const dataArr = urlString.split(',')
      const byteString = atob(dataArr[1])
      const options = {
        type: 'image/png',
        endings: 'native'
      }
      const u8Arr = new Uint8Array(byteString.length)
      for (let i = 0; i < byteString.length; i++) {
        u8Arr[i] = byteString.charCodeAt(i)
      }
      return new File([u8Arr], fileName + '.png', options) // 返回文件流
    },
    getImages (fileName) {
      html2canvas(document.querySelector('.pdf-list'), {
        dpi: 200
      }).then(canvas => {
        // console.log(canvas)
        const that = this
        canvas.toBlob(function (blob) {
          // console.log(blob)
          that.$emit('fileAdd', blob)
        }, 'image/jpeg')
      })
    },
    handleChange (file) {
      document.querySelector('.pdf-list').innerHTML = ''
      this.canvasArr = []
      let raw = file
      const fObj = new FileReader()
      fObj.readAsDataURL(raw)
      fObj.onloadend = e => {
        this.transformImage(e.target.result, file.name)
      }
    },
    async transformImage (decodedBase64, fileName) {
      const loadingTask = PDFJS.getDocument({
        url: decodedBase64,
        cMapUrl: './cmaps/', // https://unpkg.com/pdfjs-dist@2.0.943/cmaps/
        cMapPacked: true
      })
      const pdfList = document.querySelector('.pdf-list')
      loadingTask.promise.then(async (pdf) => {
        // pdf 总页数
        let pages = pdf.numPages // 声明一个pages变量等于当前pdf文件的页数
        for (let i = 1; i <= pages; i++) { // 循环页数
          let canvas = document.createElement('canvas')
          canvas.width = 200
          let page = await pdf.getPage(i) // 调用getPage方法传入当前循环的页数,返回一个page对象
          let scale = this.scale// 缩放倍数，1表示原始大小
          let viewport = page.getViewport({ scale })
          let context = canvas.getContext('2d') // 创建绘制canvas的对象
          canvas.height = viewport.height
          canvas.width = viewport.width
          canvas.style.width = '100%'
          canvas.style.height = '100%'
          let renderContext = {
            canvasContext: context,
            viewport: viewport
          }
          await page.render(renderContext)
          // canvas.setAttribute('swale')
          canvas.className = 'canvas' // 给canvas节点定义一个class名,这里我取名为canvas
          pdfList.appendChild(canvas) // 插入到pdfList节点的最后
          this.canvasArr.push(canvas)
          if (this.canvasArr.length === pages) {
            setTimeout(() => {
              this.getImages(fileName)
            }, 5000)
          }
        }
        // this.addLisenter(pdfList)
        // this.loading = false
      })
    },
    dataUrlToBold (url) {
      let arr = url.split(',')
      let mime = arr[0].match(/:(.*?);/)[1]
      let bStr = atob(arr[1])
      let n = bStr.length
      let u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bStr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    },
    addLisenter (dom) {
      dom.addEventListener('click', (e) => {
        const base64 = e.target.toDataURL('image/png')
        let blob = this.dataUrlToBold(base64)
        let obj_url = URL.createObjectURL(blob) // 消除Chrome下文件太大 导致下载失败（网络失败）的问题
        const aDom = document.createElement('a')
        aDom.href = obj_url
        aDom.download = 'bt'
        aDom.click()
      })
    },
    openModal () {
      this.visible = true
    },
    // 取消按钮
    cancel () {
      this.visible = false
    }
  }
}
</script>
<style lang="less" scoped>
.bg-img {
    margin-top: 20px;
    position: fixed;
    left: -10000px;

    /deep/ .canvas {
        cursor: pointer;
    }
}
</style>
